// response.go
package response

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// Response 统一API响应结构
type Response struct {
	Code    int    `json:"code"`            // 状态码
	Message string `json:"message"`         // 响应消息
	Error   string `json:"error,omitempty"` // 错误信息, 可选
	Data    any    `json:"data,omitempty"`  // 响应数据, 可选
}

// Success 返回成功响应
func Success(c *gin.Context, message string, data any) {
	var responseData any
	if data != nil {
		switch v := data.(type) {
		case map[string]any, []any, gin.H:
			responseData = v
		default:
			responseData = data
		}
	}

	c.JSON(http.StatusOK, Response{
		Code:    http.StatusOK,
		Message: message,
		Data:    responseData,
	})
}

// Error 返回错误响应
func Error(c *gin.Context, code int, message string, err any) {
	var errMessage string
	if e, ok := err.(error); ok {
		errMessage = e.Error()
	} else if s, ok := err.(string); ok {
		errMessage = s
	}

	c.JSON(code, Response{
		Code:    code,
		Message: message,
		Error:   errMessage,
	})
}

// 200 成功
func OK(c *gin.Context, message string, data any) {
	Success(c, message, data)
}

// 400 请求参数错误
func BadRequest(c *gin.Context, message string, err any) {
	Error(c, http.StatusBadRequest, message, err)
}

// 401 未授权
func Unauthorized(c *gin.Context, message string, err any) {
	Error(c, http.StatusUnauthorized, message, err)
}

// 201 创建成功
func Created(c *gin.Context, message string, data any) {
	c.JSON(http.StatusCreated, Response{
		Code:    http.StatusCreated,
		Message: message,
		Data:    data,
	})
}

// 404 未找到
func NotFound(c *gin.Context, message string, err any) {
	Error(c, http.StatusNotFound, message, err)
}

// 500 服务器内部错误
func ServerError(c *gin.Context, message string, err any) {
	Error(c, http.StatusInternalServerError, message, err)
}

// WithList 包装列表数据
func WithList(items any, total int) map[string]any {
	return map[string]any{
		"items": items,
		"total": total,
	}
}

// WithPagination 包装分页数据
func WithPagination(items any, page, pageSize, total int) map[string]any {
	return map[string]any{
		"items":     items,
		"page":      page,
		"pageSize":  pageSize,
		"total":     total,
		"totalPage": (total + pageSize - 1) / pageSize,
	}
}

// // 返回结构体
// user := User{ID: 1, Name: "张三"}
// response.Success(c, "获取用户成功", user)

// // 返回列表
// users := []User{{ID: 1, Name: "张三"}, {ID: 2, Name: "李四"}}
// response.Success(c, "获取用户列表成功", users)

// // 返回带总数的列表
// response.Success(c, "获取用户列表成功", response.WithList(users, len(users)))

// // 返回分页数据
// response.Success(c, "获取用户列表成功", response.WithPagination(users, 1, 10, 100))
